from sqlalchemy.orm import Session
from typing import Optional
from datetime import datetime, timedelta

from ..models import User, ApiKey
from ..config import get_password_hash, verify_password, create_access_token
from ..utils.logger import get_logger

logger = get_logger(__name__)


class AuthService:
    """认证服务类"""
    
    @staticmethod
    def register_user(db: Session, username: str, email: str, password: str) -> User:
        """注册新用户"""
        # 创建用户对象
        user = User(
            username=username,
            email=email,
            password=get_password_hash(password),
            role="user"  # 默认角色
        )
        
        db.add(user)
        db.commit()
        db.refresh(user)
        
        logger.info(f"New user registered: {username}")
        return user
    
    @staticmethod
    def authenticate_user(db: Session, username: str, password: str) -> Optional[User]:
        """验证用户凭据"""
        user = db.query(User).filter(User.username == username).first()
        if not user:
            return None
        if not verify_password(password, user.password):
            return None
        
        # 更新最后登录时间
        user.last_login = datetime.utcnow()
        db.commit()
        
        logger.info(f"User authenticated: {username}")
        return user
    
    @staticmethod
    def create_api_key(db: Session, user_id: int) -> ApiKey:
        """为用户创建API密钥"""
        import secrets
        
        # 生成API密钥
        api_key = secrets.token_urlsafe(32)
        
        # 创建API密钥记录
        new_api_key = ApiKey(
            key=api_key,
            user_id=user_id
        )
        
        db.add(new_api_key)
        db.commit()
        db.refresh(new_api_key)
        
        logger.info(f"API key created for user {user_id}")
        return new_api_key
    
    @staticmethod
    def validate_api_key(db: Session, api_key: str) -> Optional[User]:
        """验证API密钥并返回关联的用户"""
        key_record = db.query(ApiKey).filter(ApiKey.key == api_key).first()
        if not key_record:
            return None
        
        return key_record.user